package com.nbsaas.boot.script;

import javax.sql.DataSource;
import java.sql.*;

public class DatabaseScriptSource implements ScriptSource {

    private static DataSource dataSource;

    public static void setDataSource(DataSource ds) {
        dataSource = ds;
    }

    @Override
    public String getPrefix() {
        return "db:";
    }

    @Override
    public String loadScript(String path) throws Exception {
        if (dataSource == null) {
            throw new IllegalStateException("DataSource 未设置");
        }
        String actual = path.startsWith(getPrefix()) ? path.substring(getPrefix().length()) : path;
        String sql = "SELECT content FROM script_store WHERE name = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, actual);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return rs.getString("content");
            } else {
                throw new IllegalArgumentException("数据库中未找到脚本: " + actual);
            }
        }
    }
}
